package edu.hadassah.prettyprint.config;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import edu.hadassah.prettyprint.parser.XMLParser;
import edu.hadassah.prettyprint.printer.xmlprinter.NoAttributesXMLPrinter;
import edu.hadassah.prettyprint.printer.xmlprinter.NoCommentsXMLPrinter;
import edu.hadassah.prettyprint.printer.xmlprinter.SimpleXMLPrinter;
import edu.hadassah.prettyprint.printer.xmlprinter.XMLDocumentPrinter;
import edu.hadassah.prettyprint.printer.xmlprinter.XmlPrinterVisitor;

public class ApplicationContextFactory {

	
	
	/**
	 * @return
	 */
	private static XmlPrinterVisitor createDocumentPrinter(IDocumentPrinterConfig xmlpConfig) {
		XMLDocumentPrinter printer = new SimpleXMLPrinter();
		if (! xmlpConfig.isOutputAttributes()){
			printer = new NoAttributesXMLPrinter(printer);
		}
		if (! xmlpConfig.isOutputComments()){
			printer = new NoCommentsXMLPrinter(printer);
		}
		return new XmlPrinterVisitor(printer);
	}

	/**
	 * @return
	 * @throws IOException
	 */
	private static Writer createDocumentWriter(IDocumentPrinterConfig xmlpConfig) throws IOException {
		File outputFile = new File(xmlpConfig.getOutputFileName());
	
		if(outputFile.exists()){  
			boolean deleted = outputFile.delete();
			if ( !deleted ){
				throw new IOException("Failed to delete file : [" + outputFile.getCanonicalPath() +"]");
			}
		}
		boolean created = outputFile.createNewFile();
		if ( !created ){
			throw new IOException("Failed to create file : [" + outputFile.getCanonicalPath() +"]");
		}
		FileWriter fileWriter = new FileWriter(outputFile);
		return new BufferedWriter(fileWriter);
	}

	/**
	 * @param args
	 * @return
	 * @throws IOException 
	 */
	public static IApplicationContext createContextFromCmdArguments(String[] args) throws IOException {
		IDocumentPrinterConfig documentConfig = ApplicationContextUtils.getDocumentConfig(args);
		XmlFileApplicationContext applicationContext = new XmlFileApplicationContext();
		applicationContext.setDocumentPrinter(createDocumentPrinter(documentConfig));
		applicationContext.setDocumentParser(createDocumentParser(documentConfig));
		applicationContext.setDocumentReader(createDocumentReader(documentConfig));
		applicationContext.setDocumentWriter(createDocumentWriter(documentConfig));
		return applicationContext;
	}

	/**
	 * @return
	 */
	private static XMLParser createDocumentParser(IDocumentPrinterConfig documentConfig) {
		return new XMLParser();
	}

	/**
	 * @param documentConfig
	 * @return
	 * @throws FileNotFoundException
	 */
	private static BufferedReader createDocumentReader(IDocumentPrinterConfig documentConfig) 
	throws FileNotFoundException {
		return new BufferedReader(new FileReader(documentConfig.getInputFileName()));
	}

}
